/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/sort-comp */
import React, { Component } from 'react';
import { Form, Select, DatePicker, Input, Button, Spin } from 'antd';
import moment from 'moment/moment';
import { debounce } from 'lodash';
import { connect } from 'dva';
import { Yzs } from '@/components/Select';
import pageConfig from './orderPageConfig';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;
@connect(({ loading, setter, list, derivativeManage }) => ({
  setter,
  list,
  derivativeManageList: derivativeManage.derivativeManageList,
  getYzList: loading.effects['setter/getYzList'],
  getOrderRecordList: loading.effects['orderRecord/getOrderRecordList'],
  getStatisticsList: loading.effects['orderRecord/getStatisticsList'],
  operatoring: loading.effects['list/getBrandsList'],
}))
@Form.create()
export default class SearchBar extends Component {
  constructor(props) {
    super(props);
    const { sourceType } = props;
    this.pageConfig = pageConfig(sourceType);
    this.state = {
      detailed: true,
      data_start: moment()
        .startOf('day')
        .subtract(6, 'days'),
      data_end: moment()
        .endOf('day')
        .subtract(0, 'days'),
      cmId: 'all',
      brand: 'all',
      keyword: '',
      formValues: {},
      isSearch: false,
    };
  }

  componentDidMount() {
    this.getFormValues(() => {});
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.type != nextProps.type) {
      this.setState({ isSearch: false });
    }
  }

  onSearch = debounce(
    e => {
      e.preventDefault();
      const { dispatch, type, actionTypes, sourceType } = this.props;
      this.setState({ isSearch: true });
      const isWsRecord = sourceType === 'derivative' && type === 'record';
      this.getFormValues(values => {
        const url =
          type === 'record' || type === 'detail' ? actionTypes.record : actionTypes.statistics;
        dispatch({
          type: url,
          payload: {
            ...values,
            page: 1,
            ...(isWsRecord ? { is_new: 1, page_size: 100 } : {}),
          },
        });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  disabledDate = current =>
    current &&
    current >
      moment()
        .endOf('day')
        .subtract(0, 'days');

  dataClick = data => {
    const { form } = this.props;
    const setFieldsValueDate = {
      startDate: moment()
        .startOf('day')
        .subtract(data, 'days'),
      endDate: moment()
        .endOf('day')
        .subtract(data, 'days'),
    };
    form.setFieldsValue({
      date: [setFieldsValueDate.startDate, setFieldsValueDate.endDate],
    });
  };

  getFormValues = then => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format('YYYY-MM-DD'));
        const [start, end] = values.date;
        values.start_time = start;
        values.end_time = end;
        delete values.date;
      }
      this.setState({
        formValues: values,
      });
      then(values);
    });
  };

  getStationList = visible => {
    const { dispatch } = this.props;
    if (visible) {
      dispatch({
        type: 'setter/getYzList',
      });
    }
  };

  onFilterOperator = (inputValue, options) => {
    const { children } = options.props;
    if (children.indexOf(inputValue) >= 0) return true;
  };

  selectCurrency = (e, labe) => {
    this.setState({
      site_id: labe.props.value,
    });
  };

  changeSelect = value => {
    if (!value) {
      this.setState({
        site_id: 'all',
      });
    }
  };

  handleChange = value => {
    this.setState({
      brand: value,
    });
  };

  getBrandList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'list/getBrandsList',
      payload: {
        shop_id: '',
      },
    });
  };

  onWsClientDropdown = visible => {
    const { dispatch } = this.props;
    visible &&
      dispatch({
        type: 'derivativeManage/getDerivativeManagement',
        payload: {
          current: 1,
          pageSize: 200,
        },
      });
  };

  wsClientFilterOption = (input, option) =>
    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;

  render() {
    const { data_start, data_end, keyword } = this.state;
    const {
      form: { getFieldDecorator },
      type,
      getStatisticsList,
      getOrderRecordList,
      setter,
      list,
      operatoring,
      show,
      derivativeManageList,
    } = this.props;
    const { list: wsList = [] } = derivativeManageList;
    const yzList = (setter && setter.yzList) || [];
    const { brandList } = list;
    const isShow = show ? '' : 'none';
    const {
      searchBarConfig: {
        site_id: site_idConfig,
        brand: brandConfig,
        clientCascader: clientCascaderConfig,
        keyword: keywordConfig,
        allYz: yzSelectConfig,
      },
    } = this.pageConfig;
    return (
      <Form layout="inline" style={{ marginBottom: 24, display: isShow }}>
        {type == 'record' ? (
          <FormItem>
            <a style={{ marginRight: 10 }} onClick={() => this.dataClick(1)}>
              昨日
            </a>
            <a onClick={() => this.dataClick(0)}>今日</a>
          </FormItem>
        ) : null}
        <FormItem>
          {getFieldDecorator('date', {
            initialValue: [moment(data_start), moment(data_end)],
          })(
            <RangePicker
              style={{ width: '280px' }}
              placeholder={['开始日期', '结束日期']}
              disabledDate={this.disabledDate}
            />,
          )}
        </FormItem>
        {site_idConfig.show ? (
          <FormItem>
            {getFieldDecorator('site_id', {
              initialValue: 'all',
            })(
              <Select
                onDropdownVisibleChange={this.getStationList}
                filterOption={this.onFilterOperator}
                placeholder={site_idConfig.placeholder || '选择站点'}
                showSearch
                allowClear
                style={{ width: '150px' }}
                onSelect={this.selectCurrency}
                onChange={this.changeSelect}
              >
                <Option key="all" value="all">
                  {site_idConfig.all || '全部站点'}
                </Option>
                {yzList.map(({ site_id, site_name }) => (
                  <Option key={`${site_id}`} value={site_id}>
                    {site_name}
                  </Option>
                ))}
              </Select>,
            )}
          </FormItem>
        ) : null}
        {yzSelectConfig.show && (
          <FormItem>
            {getFieldDecorator('site_id', {
              initialValue: 'all',
            })(<Yzs />)}
          </FormItem>
        )}
        {brandConfig.show ? (
          <FormItem>
            {getFieldDecorator('brand', {
              initialValue: 'all',
            })(
              <Select
                onChange={this.handleChange}
                onFocus={this.getBrandList}
                showSearch
                allowClear
                placeholder="请选择品牌"
                style={{ width: 150 }}
                filterOption={this.onFilterOperator}
              >
                {operatoring ? (
                  <Option disabled value="loading">
                    <Spin />
                  </Option>
                ) : (
                  <Option key="all" value="all">
                    全部品牌
                  </Option>
                )}
                {brandList &&
                  brandList.map(({ brand_en, brand }) => (
                    <Option key={brand_en} value={brand_en}>
                      {brand}
                    </Option>
                  ))}
              </Select>,
            )}
          </FormItem>
        ) : null}
        {clientCascaderConfig.show ? (
          <FormItem>
            {getFieldDecorator(clientCascaderConfig.name)(
              <Select
                allowClear
                style={{ width: 250 }}
                placeholder={clientCascaderConfig.placeholder}
                onDropdownVisibleChange={this.onWsClientDropdown}
                filterOption={this.wsClientFilterOption}
                showSearch
              >
                {wsList.map(val => (
                  <Option key={val.ws_id} value={val.ws_id}>
                    {`${val.shop_name}+${val.phone}`}
                  </Option>
                ))}
              </Select>,
            )}
          </FormItem>
        ) : null}
        {keywordConfig.show ? (
          <FormItem>
            {getFieldDecorator(keywordConfig.name, {
              initialValue: keyword,
            })(<Input placeholder={keywordConfig.placeholder} style={{ width: 250 }} />)}
          </FormItem>
        ) : null}
        <FormItem>
          <Button
            icon="search"
            type="primary"
            loading={type == 'record' ? getOrderRecordList : getStatisticsList}
            onClick={this.onSearch}
          >
            查询
          </Button>
        </FormItem>
      </Form>
    );
  }
}
